package com.nnnu.wsnackshop.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nnnu.wsnackshop.constant.MessageConstants;
import com.nnnu.wsnackshop.constant.StatusCodeConstants;
import com.nnnu.wsnackshop.controller.base.BaseController;
import com.nnnu.wsnackshop.pojo.dto.PageDTO;
import com.nnnu.wsnackshop.pojo.entity.Favorites;
import com.nnnu.wsnackshop.pojo.vo.ProductVO;
import com.nnnu.wsnackshop.result.PageResult;
import com.nnnu.wsnackshop.result.Result;
import com.nnnu.wsnackshop.service.IFavoritesService;
import com.nnnu.wsnackshop.service.IProductsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户端-收藏 前端控制器
 * </p>
 *
 * @author zk
 * @since 2025-05-14
 */
@RestController("userFavoritesController")
@RequestMapping("/api/user/favorites")
@Tag(name = "用户端-收藏接口")
@Slf4j
@Validated
@RequiredArgsConstructor
public class FavoritesController extends BaseController {

    private final IFavoritesService favoritesService;
    private final IProductsService productsService;

    @Operation(summary = "分页获取收藏列表", description = "分页获取当前用户收藏的商品")
    @GetMapping("/page")
    public Result<PageResult<ProductVO>> getFavoritePage(@ParameterObject PageDTO pageDTO) {
        Integer userId = getUserId();
        if (userId == null) {
            return Result.error(StatusCodeConstants.UNAUTHORIZED, MessageConstants.NOT_LOGIN);
        }

        log.info("[用户端] 分页查询收藏列表 userId={}, pageDTO={}", userId, pageDTO);

        // 查询用户收藏的商品ID列表
        Page<Favorites> page = new Page<>(pageDTO.getPage(), pageDTO.getPageSize());
        LambdaQueryWrapper<Favorites> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Favorites::getUserId, userId)
                .orderByDesc(Favorites::getAddedAt);

        Page<Favorites> favoritesPage = favoritesService.page(page, wrapper);

        // 获取收藏的商品ID列表
        List<Integer> productIds = favoritesPage.getRecords().stream()
                .map(Favorites::getProductId)
                .toList();

        return Result.success(new PageResult<>(favoritesPage.getTotal(), getList(productIds)), MessageConstants.SELECT_OK);
    }

    private List<ProductVO> getList(List<Integer> productIds) {
        if (!productIds.isEmpty()) {
            return productIds.stream()
                    .map(productsService::getProductDetail)
                    .filter(p -> p != null && p.getStatus() != null && p.getStatus() == 1) // 只返回有效的商品
                    .collect(Collectors.toList());
        }
        return List.of();
    }


    @Operation(summary = "获取收藏列表", description = "获取当前用户的所有收藏")
    @GetMapping
    public Result<List<ProductVO>> getFavorites() {
        log.info("[用户端] 获取收藏列表 userId={}", getUserId());
        Integer userId = getUserId();
        if (userId == null) {
            return Result.error(StatusCodeConstants.UNAUTHORIZED, MessageConstants.NOT_LOGIN);
        }

        // 查询用户收藏的商品ID列表
        LambdaQueryWrapper<Favorites> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Favorites::getUserId, userId)
                .orderByDesc(Favorites::getAddedAt);

        List<Favorites> favoritesList = favoritesService.list(wrapper);

        // 获取收藏的商品ID列表
        List<Integer> productIds = favoritesList.stream()
                .map(Favorites::getProductId)
                .toList();

        return Result.success(getList(productIds), MessageConstants.SELECT_OK);
    }

    @Operation(summary = "获取收藏数量", description = "获取当前用户的收藏总数")
    @GetMapping("/count")
    public Result<Integer> getFavoriteCount() {
        Integer userId = getUserId();
        if (userId == null) {
            return Result.success(StatusCodeConstants.UNAUTHORIZED, MessageConstants.OPERATION_SUCCESSFUL);
        }

        LambdaQueryWrapper<Favorites> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Favorites::getUserId, userId);
        long count = favoritesService.count(wrapper);
        return Result.success(StatusCodeConstants.SUCCESS, Math.toIntExact(count), MessageConstants.SELECT_OK);
    }

    @Operation(summary = "检查商品是否已被收藏", description = "检查当前用户是否已收藏指定商品")
    @GetMapping("/check/{productId}")
    public Result<Boolean> checkFavorite(
            @PathVariable("productId") @Parameter(description = "商品ID", in = ParameterIn.PATH) Integer productId) {
        Integer userId = getUserId();
        if (userId == null) {
            return Result.success(false, MessageConstants.OPERATION_SUCCESSFUL); // 未登录视为未收藏
        }
        Boolean isFavorite = favoritesService.checkFavorite(userId, productId);
        return Result.success(isFavorite, MessageConstants.OPERATION_SUCCESSFUL);
    }

    @Operation(summary = "添加商品到收藏", description = "将指定商品添加到当前用户的收藏列表")
    @PostMapping("/{productId}")
    public Result<Void> addFavorite(
            @PathVariable @Parameter(description = "商品ID", in = ParameterIn.PATH) Integer productId) {
        Integer userId = getUserId();
        if (userId == null) {
            return Result.error(StatusCodeConstants.UNAUTHORIZED, MessageConstants.NOT_LOGIN);
        }
        favoritesService.addFavorite(userId, productId);
        return Result.success(MessageConstants.ADD_OK);
    }

    @Operation(summary = "从收藏中移除商品", description = "从当前用户的收藏列表中移除指定商品")
    @DeleteMapping("/{productId}")
    public Result<Void> removeFavorite(@PathVariable("productId") @Parameter(description = "商品ID") Integer productId) {
        Integer userId = getUserId();
        if (userId == null) {
            return Result.error(StatusCodeConstants.UNAUTHORIZED, MessageConstants.NOT_LOGIN);
        }
        favoritesService.removeFavorite(userId, productId);
        return Result.success(MessageConstants.DELETE_OK);
    }
}